package cn.kgc.chlm.filter;

import cn.kgc.chlm.entity.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //ServletRequest强转为HttpServletReqest
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        //获取HttpSession对象
        HttpSession session = request.getSession();
        //获取我们当前请求的uri
        String requestURI = request.getRequestURI();
        //如果请求地址包含这几个关键字，则直接放行
        if (requestURI.contains("/home") || requestURI.contains("user") || requestURI.contains("menu")){
            filterChain.doFilter(servletRequest, servletResponse);
        }else {
            //通过Session对象查看用户是否登录
            User user = (User) session.getAttribute("user");
            if(user != null){
                //如果登录了，则放行
                filterChain.doFilter(servletRequest, servletResponse);
            }else {
                //没有登录，转发到登录页面提示登录
                request.setAttribute("msg","您需要先登录后在来");
                request.getRequestDispatcher("/WEB-INF/pages/login.jsp").forward(servletRequest,servletResponse);
            }
        }




    }

    @Override
    public void destroy() {

    }
}
